
package com.yxjx.duoxue.course;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.Executors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.tencent.stat.StatService;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.JumpActivity;
import com.yxjx.duoxue.PageLoading;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.YxApplication;
import com.yxjx.duoxue.course.datamodel.AdDTS;
import com.yxjx.duoxue.customview.TwoColumnListView;
import com.yxjx.duoxue.customview.TwoColumnListView.CallbackForSelection;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnLoadListener;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnRefreshListener;
import com.yxjx.duoxue.datamodel.DMBaiduLocation;
import com.yxjx.duoxue.datamodel.DMSortBy;
import com.yxjx.duoxue.datamodel.DataList;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.datamodel.school.DMSchool;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.push.PushHelper;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

/**
 * Course／School List Activity
 * @author mengmengchen
 *
 */
public class CourseListActivity extends BaseActionBarActivity implements
		OnRefreshListener, OnLoadListener {
	
	private static final int MSG_CODE_LOAD_FILTERS_CONDITIONS_DONE = 1;
	
	private static final int DOUBLE_OFFSET = 0;
	private static final int HALF_OFFSET = 0;
	
	// used to record user's selection for search condition.
	public static final int TAB_UNSELECTED = -1;
	public static final int TAB_COURSE = 0;
	public static final int TAB_AREA = 1;
	public static final int TAB_AGE = 2;
	public static final int TAB_SMART = 3;
	
	// 记录head tab status
	public static final int HEAD_TAB_COURSE = 0;
	public static final int HEAD_TAB_SCHOOL = 1;
	
	// 课程列表包含 课程项 和广告项两种，只有一个广告项并且置顶。
	private static final int TYPE_COUNT_COURSE_LIST = 2;
	private static final int TYPE_COURSE_LIST_COURSE = 0;
	private static final int TYPE_COURSE_LIST_AD = 1;
	
	private AutoListView mListCourse;
	private AutoListView mListSchool;
	private PopupWindow mPopupWindow;
	private Dialog mDialog;
	private TextView mSearchBox;
	private SchoolAdapter mSchoolAdapter;
	private Context mContext;

	private boolean loadFilterConditionDone = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setCustomActionBar(R.layout.head_course_list_both);
		setContentView(R.layout.fragment_course_list);
		mContext = this;
		mSearchCondition = new SearchCondition(this);
		mSearchFilterBottomView = findViewById(R.id.search_filter_bottom);
		
		// init head tabs.
		initHeadTabs();
		showLoading(true);
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				PageLoading.getAreasInfo(CourseListActivity.this);
				PageLoading.getCourseCategory(CourseListActivity.this);
				PageLoading.getSortBys(CourseListActivity.this);
				mInitHander.sendEmptyMessage(MSG_CODE_LOAD_FILTERS_CONDITIONS_DONE);
			}
		});
		thread.setPriority(Thread.MAX_PRIORITY);
		thread.start();
	}

	public void onLoadFilterConditionsDone() {
		Bundle extra = getIntent().getExtras();
		if (extra != null) {
			String category = (String) extra.get(HomePageFragment.EXTRA_SEARCH_CATEGORY);
			if (UIHelper.isEmpty(category)) {
				category = getResources().getString(R.string.course_type);
			} else {
				UIHelper.setText(findViewById(R.id.head1), R.id.condition1, category);
				int categoryId = (Integer) extra.get(HomePageFragment.EXTRA_SEARCH_CATEGORY_ID);
				mSearchCondition.resetCategory(categoryId, mHeadTabSelected);
			}
			
			// customize search box text
			String keywords = getIntent().getStringExtra(Yx.EXTRA_SEARCH_KEY_WORDS);
			if (!UIHelper.isEmpty(keywords)) {
				findViewById(R.id.search_box).setVisibility(View.VISIBLE);
				UIHelper.setText(findViewById(R.id.root), R.id.search_box, "当前搜索：" + keywords);
				mSearchCondition.setKeyword(keywords);
			}
			
		}
		// customize default区域信息为附近
		String area = "附近";
		UIHelper.setText(findViewById(R.id.head2), R.id.condition2, area);
		mSearchCondition.resetArea(area);
		
		// 显示当前位置与显示搜索关键字二选一
		showLocationButton(findViewById(R.id.search_box).getVisibility() != View.VISIBLE);

		mListCourse = (AutoListView) findViewById(R.id.list_course);
		mListSchool = (AutoListView) findViewById(R.id.list_school);
		
		mCourseAdapter = new CourseAdapter();
		mSchoolAdapter = new SchoolAdapter();
		
		mListSchool.setAdapter(mSchoolAdapter);
		mListSchool.setOnRefreshListener(this);
		mListSchool.setOnLoadListener(this);
		
		mListCourse.setAdapter(mCourseAdapter);
		mListCourse.setOnRefreshListener(this);
		mListCourse.setOnLoadListener(this);
		
		selectHeadTab(mActionBar.getCustomView().findViewById(R.id.search_course));
		
		mListCourse.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				
				// avoid null point exception. 上下滑动的List，会多处首尾两个item。
				if (position >= mCourseAdapter.getCount() + 1 || position == 0) {
					return;
				}
				
				int actualPosition = position - 1;
				
				if (mCourseAdapter.getItemViewType(actualPosition) == TYPE_COURSE_LIST_COURSE) {
					Intent intent = new Intent();
					DMCourse course = mCourseAdapter.getCourse(actualPosition - mCourseAdapter.getAdCount());
					intent.putExtra(NwUtils.KEY_ID, "" + course.getCourseId());
					intent.setClass(getApplicationContext(), CourseIntroductionActivity.class);
					StatHelper.addKVEvent(mContext, "event_course_list_click",
							StatHelper.KEY_COURSE, course.getCourseId());
					startActivity(intent);
				} else if (mCourseAdapter.getItemViewType(actualPosition) == TYPE_COURSE_LIST_AD) {
					AdDTS adItem = mCourseAdapter.getAdItem();
					PushHelper.pushActivity(CourseListActivity.this, PushHelper.AdDTS2Custom(adItem));
				}
			}
		});
		
		mListSchool.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// avoid null point exception.
				if (arg2 >= mSchoolAdapter.getCount() + 1 || arg2 == 0) {
					return;
				}
				
				Intent intent = new Intent();
				DMSchool school = mSchoolAdapter.getSchool(arg2 - 1);
				intent.putExtra(NwUtils.KEY_ID, "" + school.getId());
				intent.setClass(getApplicationContext(), SchoolIntroductionActivity.class);
				StatHelper.addKVEvent(mContext, "event_school_list_click",
						StatHelper.KEY_SCHOOL, school.getId());
				startActivity(intent);
				
			}
		});
		
		int[] ids = new int[] {
				R.id.head1,
				R.id.head2,
				R.id.head3,
				R.id.head4
		};
		for (int id : ids) {
			UIHelper.setClickListener(findViewById(R.id.course_list), id, mClickListener);
		}
		
		int[] headIds = new int[] {
				R.id.search_root
		};
		for (int id : headIds) {
			UIHelper.setClickListener(mActionBar.getCustomView(), id, mClickListener);
		}
		
		// register location change
		Utils.registerPreferenceChangeListener(this, mLocationChangeListener);
		loadFilterConditionDone  = true;
	}
	
	private void showLoading(boolean showLoading) {
		findViewById(R.id.loading).setVisibility(showLoading ? View.VISIBLE : View.INVISIBLE);
		findViewById(R.id.course_list).setVisibility(showLoading ? View.INVISIBLE : View.VISIBLE);
	}
	
	// 重新请求位置定位
	public void reLocation(View view) {
		StatHelper.addKVEvent(mContext, "event_course_address_refresh");
		showLoading(true);
		// 百度地图请求位置信息
		if (getApplication() instanceof YxApplication) {
			Utils.logd("CMM7 relocation");
			YxApplication app = (YxApplication) getApplication();
			app.requestRelocation();
		}
		
		// update UI
		TextView text = (TextView) findViewById(R.id.relocation_text);
		text.setText("当前位置：定位中...");
		View icon = findViewById(R.id.relocation_icon);
		Animation anim = AnimationUtils.loadAnimation(this, R.anim.anim_rotate_refresh);
		icon.startAnimation(anim);
	}
	
	private SharedPreferences.OnSharedPreferenceChangeListener mLocationChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {

		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreference, String key) {
			
			DMBaiduLocation location = DMBaiduLocation.forceGetLocationFromSharedPreference(CourseListActivity.this);
			Utils.logd("CMM7 forceGetLocation = " + location);
			onRelocationDone(location);
		}
	};
	
	private void onRelocationDone(DMBaiduLocation location) {
		TextView text = (TextView) findViewById(R.id.relocation_text);
		if (location == null) {
			text.setText("当前位置：获取位置失败");
		} else {
			String addrStr = location.getAddrStr();
			text.setText("当前位置：" + (UIHelper.isEmpty(addrStr) ? "未知位置" : addrStr));
		}
		View icon = findViewById(R.id.relocation_icon);
		icon.clearAnimation();
//		mCourseAdapter.notifyDataSetInvalidated();
//		mSchoolAdapter.notifyDataSetInvalidated();
		
		// 重新请求数据而不只是刷新距离信息。
		forceToReloadData();
	}
	
	private void showLocationButton(boolean showLocation) {
		findViewById(R.id.search_box).setVisibility(showLocation ? View.INVISIBLE : View.VISIBLE);
		findViewById(R.id.relocation).setVisibility(showLocation ? View.VISIBLE : View.INVISIBLE);
		DMBaiduLocation location = Globals.getInstance(this).getLocation();
		String locText = location == null ? "定位失败" : location.getAddrStr();
		UIHelper.setText(findViewById(R.id.relocation), R.id.relocation_text, "当前位置：" + (UIHelper.isEmpty(locText) ? "未知位置" : locText));
	}
	
	// 重新更新学校
	private void loadingAllSchoolData(int callbackId) {
		JSONObject params = mSearchCondition.getQueryCondition(mHeadTabSelected);
		loadingDataFromServer(NwUtils.REQ_SCHOOL_LIST, params.toString(), String.valueOf(callbackId));
	}
	
	// 加载更多学校
	private void loadingMoreSchoolData(int callbackId) {
		JSONObject params = mSearchCondition.getQueryCondition(mHeadTabSelected);
		try {
			params.put(NwUtils.KEY_START_INDEX, "" + (mSchoolAdapter.getCount() + 1));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		loadingDataFromServer(NwUtils.REQ_SCHOOL_LIST, params.toString(), String.valueOf(callbackId));
	}
	
	// 重新更新课程
	private void loadingAllCourseData(int callbackId) {
		JSONObject params = mSearchCondition.getQueryCondition(mHeadTabSelected);
		loadingDataFromServer(NwUtils.REQ_COURSE_LIST, params.toString(), String.valueOf(callbackId));
	}
	
	// 加载更多课程
	private void loadingMoreCourseDataFromStartIndex(int callbackId) {
		JSONObject params = mSearchCondition.getQueryCondition(mHeadTabSelected);
		try {
			params.put(NwUtils.KEY_START_INDEX, "" + (mCourseAdapter.getCount() + 1));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		loadingDataFromServer(NwUtils.REQ_COURSE_LIST, params.toString(), String.valueOf(callbackId));
	}

	private void loadingDataFromServer(String requestUrl, String params, String callbackId) {
		if (NwUtils.REQ_SCHOOL_LIST.equals(requestUrl)) {
			if (mLoadingSchoolAsyncTask != null) {
				mLoadingSchoolAsyncTask.cancel(true);
			}
			mLoadingSchoolAsyncTask = new LoadingAsyncTask<DMSchool>();
			mLoadingSchoolAsyncTask.execute(requestUrl, params.toString(), "" + callbackId);
		} else if (NwUtils.REQ_COURSE_LIST.equals(requestUrl)) {
			if (mLoadingCourseAsyncTask != null) {
				mLoadingCourseAsyncTask.cancel(true);
			}
			mLoadingCourseAsyncTask = new LoadingAsyncTask<DMCourse>();
			mLoadingCourseAsyncTask.execute(requestUrl, params.toString(), "" + callbackId);
		}
	}
	
	class CourseAdapter extends BaseAdapter {
		
		private DataList<DMCourse> mCourseArray = new DataList<DMCourse>();
		
		// 刷新记录
		public void setCourses(DataList<DMCourse> courses) {
			mCourseArray = courses;
			AdDTS adItem = mCourseArray.getAdItem();
			notifyDataSetChanged();
		}
		
		// 加载更多
		public void addCourse(DataList<DMCourse> courses) {
			mCourseArray.addAll(courses);
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			int courseCount = getCourseCount();
			int adCount = getAdCount();
			return courseCount + adCount;
		}
		
		@Override
		public int getViewTypeCount() {
			return TYPE_COUNT_COURSE_LIST;
		}
		
		@Override
		public int getItemViewType(int position) {
			if (getAdCount() == 1 && position == 0) {
				return TYPE_COURSE_LIST_AD;
			}
			return TYPE_COURSE_LIST_COURSE;
		}

		private int getCourseCount() {
			return mCourseArray == null ? 0 : mCourseArray.size();
		}

		private int getAdCount() {
			return (mCourseArray == null || mCourseArray.getAdItem() == null) ? 0 : 1;
		}
		
		public DMCourse getCourse(int index) {
			return mCourseArray.get(index);
		}
		
		public AdDTS getAdItem() {
			if (getAdCount() == 0) {
				return null;
			}
			return mCourseArray.getAdItem();
		}

		@Override
		public View getView(int position, View arg1, ViewGroup arg2) {
			View item = null;
			if (getItemViewType(position) == TYPE_COURSE_LIST_COURSE) {
				
				if (arg1 == null) {
					item = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_course_list, null);
				} else {
					item = arg1;
				}
				final DMCourse course = mCourseArray.get(position - getAdCount());
				customizeCourseItem(item, course);
			} else if (getItemViewType(position) == TYPE_COURSE_LIST_AD) {
				if (arg1 == null) {
					item = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_course_list_ad, null);
				} else {
					item = arg1;
				}
				AdDTS adItem = mCourseArray.getAdItem();
				UIHelper.setText(item, R.id.title, adItem.getAdTitle());
				UIHelper.setText(item, R.id.desc, adItem.getAdDes());
				UIHelper.asyncLoadImage((ImageView) item.findViewById(R.id.icon), adItem.getAdImage(), R.drawable.default_icon);
			}
			return item;
		}


		
		
		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}
		
	}
	
	public static void customizeCourseItem(View item, final DMCourse course) {
		UIHelper.setText(item, R.id.course_name, course.getCourseName());
		((RatingBar) item.findViewById(R.id.rating_bar)).setRating(Float.valueOf(course.getCourseCommentLevel().getAvgTotalLevel()));
		UIHelper.setText(item, R.id.school_name, course.getSchoolFullName());
		int supportBook = course.getSupportBook();
		item.findViewById(R.id.free_auditon).setVisibility(supportBook == 1 ? 
				View.VISIBLE : View.GONE);
		UIHelper.asyncLoadImage((ImageView) item.findViewById(R.id.icon), course.getHeadImageUrl(), R.drawable.default_icon);
		((TextView) item.findViewById(R.id.visit_count)).setText(Utils.getStyleString(course.getCourseCommentLevel().getVisitCount()));
		((TextView) item.findViewById(R.id.location_info)).setText(Utils.getDistanceDesc(item.getContext(), course.getSchoolGps()));
		Utils.addLabels((ViewGroup) item.findViewById(R.id.labels), course.getAuthArray());
		((TextView) item.findViewById(R.id.discount_info)).setText(course.getDiscount());
	}
	
	class SchoolAdapter extends BaseAdapter {
		
		private ArrayList<DMSchool> mSchoolsArray = new ArrayList<DMSchool>();
		
		// 加载更多
		public void addData(ArrayList<DMSchool> items) {
			mSchoolsArray.addAll(items);
			notifyDataSetChanged();
		}
		
		// 全部刷新
		public void setData(ArrayList<DMSchool> items) {
			mSchoolsArray = items;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mSchoolsArray == null ? 0 : mSchoolsArray.size();
		}
		
		public DMSchool getSchool(int index) {
			return mSchoolsArray.get(index);
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_school_list, null);
			} else {
				ret = arg1;
			}
			DMSchool school = mSchoolsArray.get(arg0);
			UIHelper.setText(ret, R.id.school_name, school.getFullSchoolName());
			UIHelper.setText(ret, R.id.course_types, school.getCoursesText());
			((TextView) ret.findViewById(R.id.location_info)).setText(Utils.getDistanceDesc(getApplicationContext(), school.getSchoolGps()));
			((RatingBar) ret.findViewById(R.id.rating_bar)).setRating(Float.valueOf(school.getSchoolCommentLevel().getAvgTotalLevel()));
			((TextView) ret.findViewById(R.id.visit_count)).setText(Utils.getStyleString(school.getSchoolCommentLevel().getVisitCount()));
			UIHelper.asyncLoadImage((ImageView) ret.findViewById(R.id.icon), school.getSchoolImage(), R.drawable.default_icon);
			Utils.addLabels((ViewGroup) ret.findViewById(R.id.labels), school.getAuthArray());
			return ret;
		}
		
		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}
		
	}
	
	private void initPopupWindow(int sugW, int sugH, int layoutId) {
		View customView = getPopWindowCustomView(layoutId);
		mPopupWindow = new PopupWindow(customView, sugW, sugH);
		customView.setOnTouchListener(onPopWindowTouchListener);

		mPopupWindow.setTouchable(true);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setFocusable(true);
//		mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
//				android.R.color.transparent));
		ColorDrawable dw = new ColorDrawable(0x90000000);
		mPopupWindow.setBackgroundDrawable(dw);

		Window window = getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.dimAmount = .5f;
		window.setAttributes(lp);
	}

	private View getPopWindowCustomView(int layoutId) {
		View customView = LayoutInflater.from(getApplicationContext()).inflate(
				layoutId, null, false);
		switch (layoutId) {
		case R.layout.segment_search_condition_area_1:
		case R.layout.segment_search_condition_area_2:
		case R.layout.segment_search_condition_area:
			break;
		default:
			break;
		}
		return customView;
	}
	
	private void clickSearchTab(View view, int id) {
		
		
//		if (mTabSelected == TAB_UNSELECTED || mTabSelected != getTabSelected(id)) {
//			mTabSelected = getTabSelected(id);
//		}
//		// 如果之前选择的查询条件是当前的选择
//		else if (mTabSelected == getTabSelected(id)) {
//			mTabSelected = TAB_UNSELECTED;
//		}
		
		int oldTabSelected = mTabSelected;
		mTabSelected = getTabSelected(id);
		// 如果dialog没显示则显示，已经显示则消失。
		if (mTabSelected != TAB_UNSELECTED) {
			if (mPopupWindow == null || !mPopupWindow.isShowing()) {
				tryShowDialog(mSearchFilterBottomView);
			} else {
				dismissPopupWindowIfHave();
			}
		}
	}


	private void tryShowDialog(View view) {
		// 获取期望window大小
		int[] sizes = Utils.getDisplayWidthHeight(this);
		int[] viewPosition = new int[2];
		view.getLocationOnScreen(viewPosition);
		int windowHeight = sizes[1] - viewPosition[1] - view.getHeight();
		
		if (mPopupWindow == null || !mPopupWindow.isShowing()) {
			initPopupWindow((int) (sizes[0] - DOUBLE_OFFSET),
					windowHeight, getLayoutIdByTab(mTabSelected));

			mDialog = new Dialog(this,
					android.R.style.Theme_Translucent_NoTitleBar);
			WindowManager.LayoutParams lp = mDialog.getWindow()
					.getAttributes();
			lp.dimAmount = 0.5f;
			mDialog.getWindow().setAttributes(lp);
			mDialog.getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_DIM_BEHIND);
			mDialog.setCanceledOnTouchOutside(true);
			mPopupWindow.showAsDropDown(view, HALF_OFFSET, 0);
		} 

		View root = mPopupWindow.getContentView();
		// single column list
		if (mTabSelected == TAB_SMART || mTabSelected == TAB_AGE) {
			root.findViewById(R.id.segment_search_condition_area_1)
					.setVisibility(View.INVISIBLE);
			root.findViewById(R.id.segment_search_condition_area_2)
					.setVisibility(View.VISIBLE);
			
			ListView mSingleList = (ListView) root.findViewById(R.id.list);
			if (mTabSelected == TAB_AGE) {
				int initIndex = mSearchCondition.getSelectedIndexOfColumn3();
				SingleListAdapter adapter = new SingleListAdapter(initIndex);
				adapter.setData(mData3);
				mSingleList.setAdapter(adapter);
				// 用来调整选中项在list中的位置（默认选中第四个的位置）。
				mSingleList.setSelection(initIndex < 3 ? 0 : initIndex - 3);
			} else if (mTabSelected == TAB_SMART) {
				int initIndex = mSearchCondition.getColumn4SortBy(mHeadTabSelected);
				SingleListAdapter adapter = new SingleListAdapter(initIndex);
				adapter.setData(getSortByArray());
				mSingleList.setAdapter(adapter);
				// 用来调整选中项在list中的位置（默认选中第四个的位置）。
				mSingleList.setSelection(initIndex < 3 ? 0 : initIndex - 3);
			}
			mSingleList.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// update 查询条件的text
					if (mTabSelected == TAB_AGE) {
						UIHelper.setText(findViewById(R.id.head3), R.id.condition3, 
								SearchCondition.getTag(CourseListActivity.this, mHeadTabSelected, mTabSelected, arg2, 0));
						if (arg2 == 0) {
							mSearchCondition.setColumn3Ignore(true);
						} else {
							// 服务器所使用的区间前为闭区间，后为开区间
							mSearchCondition.setColumn3Ignore(false);
							mSearchCondition.setStartAge(SearchCondition.indexToBeginAge(arg2));
							mSearchCondition.setEndAge(SearchCondition.indexToEndAge(arg2));
						}
					} else if (mTabSelected == TAB_SMART) {
						UIHelper.setText(findViewById(R.id.head4), R.id.condition4, 
								SearchCondition.getTag(CourseListActivity.this, mHeadTabSelected, mTabSelected, arg2, 0));
						mSearchCondition.setColumn4SortBy(arg2, mHeadTabSelected);
					}
					selectedDone();
					// load data.
					loadingAllData(mHeadTabSelected, AutoListView.REFRESH);
				}
			});

		// Two Column list 
		} else {
			root.findViewById(R.id.segment_search_condition_area_1)
					.setVisibility(View.VISIBLE);
			root.findViewById(R.id.segment_search_condition_area_2)
					.setVisibility(View.INVISIBLE);
			
			TwoColumnListView mTwoColums = (TwoColumnListView) root.findViewById(R.id.twoColumnListView1);

			if (mTabSelected == TAB_COURSE) {
				int[] curIndexs = mSearchCondition.getSelectedIndexOfColumn2();
				mTwoColums.setData(Globals.getInstance(this).getCourseTpes(), curIndexs[0], curIndexs[1]);
			} else if (mTabSelected == TAB_AREA) {
				int[] curIndexs = mSearchCondition.getSelectedIndexOfColumn1();
				mTwoColums.setData(Globals.getInstance(this).getAreasInfo(), curIndexs[0], curIndexs[1]);
			}
			
			mTwoColums.setCallback(new CallbackForSelection() {
				
				@Override
				public void selected(int column1, int column2) {
					if (column1 == 0) {
						// 全部Item
						if (mTabSelected == TAB_COURSE) {
							mSearchCondition.setCourseTypeIgnore(true);
							UIHelper.setText(findViewById(R.id.head1), R.id.condition1,
									getResources().getString(R.string.course_type));
						} else if (mTabSelected == TAB_AREA) {
							mSearchCondition.setAreaIgnore(true);
							UIHelper.setText(findViewById(R.id.head2), R.id.condition2, 
									getResources().getString(R.string.area_type));
						}
					} else {
						// update查询条件text
						if (mTabSelected == TAB_COURSE) {
							UIHelper.setText(findViewById(R.id.head1), R.id.condition1, 
									SearchCondition.getTag(CourseListActivity.this, mHeadTabSelected, mTabSelected, column1, column2));
							mSearchCondition.setCourseTypeIgnore(false);
							mSearchCondition.setCourseCategoryOne(column1);
							mSearchCondition.setCourseCategoryTwo(column2);
							
						} else if (mTabSelected == TAB_AREA) {
							UIHelper.setText(findViewById(R.id.head2), R.id.condition2, 
									SearchCondition.getTag(CourseListActivity.this, mHeadTabSelected, mTabSelected, column1, column2));
							
							mSearchCondition.setAreaIgnore(false);
							mSearchCondition.setAreaCategoryOne(column1);
							mSearchCondition.setAreaCategoryTwo(column2);
						}
					}
					
					selectedDone();
					// loading data
					loadingAllData(mHeadTabSelected, AutoListView.REFRESH);
				}
			});
		}
	}
	
	private void dismissPopupWindowIfHave() {
		mTabSelected = TAB_UNSELECTED;
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
		}
	}
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.search_root:
				Intent intent = new Intent(getApplicationContext(), CourseSearchActivity.class);
				startActivity(intent);
				break;
			case R.id.head1:
			case R.id.head2:
			case R.id.head3:
			case R.id.head4:
				clickSearchTab((View) arg0.getParent(), arg0.getId());
				break;
			case R.id.search_course:
			case R.id.search_school:
				if (loadFilterConditionDone) {
					// 基本条件加载完才允许切换列表
					selectHeadTab(arg0);
				}
				break;
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
			
		}
	};
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		default:
			break;
		}
	};
	
	private int mTabSelected = TAB_UNSELECTED;
	private OnTouchListener onPopWindowTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (mPopupWindow != null && mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
				mPopupWindow = null;
			}
			return false;
		}
	};
	
	private int getTabSelected(int viewId) {
		if (viewId == R.id.head1) {
			return TAB_COURSE;
		} else if (viewId == R.id.head2) {
			return TAB_AREA;
		} else if (viewId == R.id.head3) {
			return TAB_AGE;
		} else if (viewId == R.id.head4) {
			return TAB_SMART;
		}
		return TAB_UNSELECTED;
	}
	
	private int getLayoutIdByTab(int tabSelected) {
		int ret = 0;
		switch (tabSelected) {
		case TAB_COURSE:
		case TAB_AREA:
			ret = R.layout.segment_search_condition_area_1;
			break;
		case TAB_AGE:
		case TAB_SMART:
		default:
			ret = R.layout.segment_search_condition_area_2;
			break;
		}
		return R.layout.segment_search_condition_area;
	}
	
	
	private void hideIME() {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
		imm.hideSoftInputFromWindow(mSearchBox.getWindowToken(), 0);
	}
	
	private void selectedDone() {
		// / MTA stat start
		Properties prop = StatHelper.getBasicProp(CourseListActivity.this);
		prop.put(StatHelper.KEY_SORT_BY, mTabSelected);
		StatService.trackCustomKVEvent(CourseListActivity.this, "event_course_sort_by_click", prop);
		// / MTA stat end
		
		dismissPopupWindowIfHave();
		mTabSelected = TAB_UNSELECTED;
		showLoading(true);
	}

	private String[][] mData1 = new String[][] {
			{"全部"},
			{"启蒙教育", "全部", "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部",  "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"},
			{"启蒙教育", "全部",  "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部", "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"},
			{"启蒙教育", "全部",  "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部", "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"},
			{"启蒙教育", "全部",  "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部", "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"},
			{"启蒙教育", "全部",  "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部",  "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"}
	};
	
	private String[][] mData2 = new String[][] {
			{"全部"},
			{"海淀", "全部", "苏州街","中关村","芍药居","知春路", "苏州街","中关村","芍药居","知春路"},
			{"朝阳", "全部", "苏州街","中关村","芍药居","知春路", "苏州街","中关村","芍药居","知春路"},
			{"西城", "全部", "中关村","芍药居","知春路", "苏州街","中关村","芍药居","知春路"},
			{"东城", "全部", "中关村","芍药居","知春路", "苏州街","中关村","芍药居","知春路"},
			{"昌平", "全部", "芍药居","知春路", "苏州街","中关村","芍药居"},
			{"大兴", "全部", "苏州街","中关村","芍药居","知春路", "苏州街","中关村","芍药居","知春路"},
	};
	
	private ArrayList<String> mData3 = SearchCondition.getAges();
	
//	private String[] mData4 = new String[] {
//			"智能排序", "最新发布", "收藏最多", "免费试听"
//	};
	
	private ArrayList<String> getSortByArray() {
		if (mHeadTabSelected == HEAD_TAB_COURSE) {
			ArrayList<DMSortBy> sortBys = Globals.getInstance(this).getSortBysCourse();
			if (sortBys == null) {
				return null;
			}
			ArrayList<String> strs = new ArrayList<String>();
			for (DMSortBy item : sortBys) {
				strs.add(item.getSortByDesc());
			}
			return strs;
			
		} else if (mHeadTabSelected == HEAD_TAB_SCHOOL) {
			ArrayList<DMSortBy> sortBys = Globals.getInstance(this).getSortBysSchool();
			if (sortBys == null) {
				return null;
			}
			ArrayList<String> strs = new ArrayList<String>();
			for (DMSortBy item : sortBys) {
				strs.add(item.getSortByDesc());
			}
			return strs;
		}
		return null;
	}
	
	private CourseAdapter mCourseAdapter;
	
	class SingleListAdapter extends BaseAdapter {
		
		private ArrayList<String> mData;
		private int mSelectedIndex = -1;
		
		public SingleListAdapter(int index) {
			mSelectedIndex = index;
		}

		@Override
		public int getCount() {
			return mData == null ? 0 : mData.size();
		}
		
		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_search_condition_2, null);
			} else {
				ret = arg1;
			}
			UIHelper.setText(ret, R.id.text, mData.get(arg0));
			ret.findViewById(R.id.text).setSelected(mSelectedIndex == arg0);
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		public ArrayList<String> getData() {
			return mData;
		}

		public void setData(ArrayList<String> data) {
			this.mData = data;
		}

		public int getSelectedIndex() {
			return mSelectedIndex;
		}

		public void setSelectedIndex(int mSelectedIndex) {
			this.mSelectedIndex = mSelectedIndex;
		}
	}
	
	class LoadingAsyncTask<E> extends AsyncTask<String, Integer, DataList<E>> {
		
		private int mCallbackId = -1;
		private String mURL = "";

		@Override
		protected DataList<E> doInBackground(String... arg0) {
			DataList<E> courses = new DataList<E>();
			
			if (isCancelled()) {
				return null;
			}
			try {
				
				String url = arg0[0];
				mURL = url;
				JSONObject jo = null;
				if (!UIHelper.isEmpty(arg0[1])) {
					jo = new JSONObject(arg0[1]);
				}
				// 学校和课程搜索时加入可选查询条件《本地的位置信息》,供搜索附近机构时候使用。
				DMBaiduLocation location = DMBaiduLocation.getLocation(getApplicationContext());
				if (location != null) {
					jo.put("gps", "" + location.getLatitude() + "," + location.getLongtitude());
				}
				
				courses = NwUtils.requestDataInfoList(url, jo,
						UserLoginResponse.getInstance(getApplicationContext()),
						getApplicationContext());
				mCallbackId = Integer.valueOf(arg0[2]);
				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return courses;
		}
		
		@Override
		protected void onPostExecute(DataList<E> result) {
			
			if (isCancelled()) {
				return;
			}
			
			super.onPostExecute(result);
			int headTab = -1;
			if (NwUtils.REQ_COURSE_LIST.equals(mURL)) {
				if (mCallbackId == AutoListView.REFRESH) {
					if (result == null || result.size() == 0) {
						showEmpty(true, false);
					} else {
						showEmpty(false, true);
					}
					mCourseAdapter.setCourses((DataList<DMCourse>) result);
					mListCourse.post(new Runnable() {
						@Override
						public void run() {
							mListCourse.setSelection(0);
						}
					});
					
				} else if (mCallbackId == AutoListView.LOAD) {
					mCourseAdapter.addCourse((DataList<DMCourse>) result);
				}
				headTab = HEAD_TAB_COURSE;
			} else if (NwUtils.REQ_SCHOOL_LIST.equals(mURL)) {
				if (mCallbackId == AutoListView.REFRESH) {
					if (result == null || result.size() == 0) {
						showEmpty(true, false);
					} else {
						showEmpty(false, false);
					}
					mSchoolAdapter.setData((ArrayList<DMSchool>) result);
					mListSchool.post(new Runnable() {
						@Override
						public void run() {
							mListSchool.setSelection(0);
						}
					});
					
				} else if (mCallbackId == AutoListView.LOAD) {
					mSchoolAdapter.addData((ArrayList<DMSchool>) result);
				}
				headTab = HEAD_TAB_SCHOOL;
			}
			
			// callback to notify AutoListView to update.
			Message msg = handler.obtainMessage();
			msg.what = mCallbackId;
			msg.obj = result;
			msg.arg1 = headTab;
			handler.sendMessage(msg);
			// dismiss loading dialog.
			showLoading(false);
			
		}
	}
	
	/**
	 * 有限判断是否为空，其次判断是否要显示课程
	 * @param isEmpty
	 * @param showCourse
	 */
	private void showEmpty(boolean isEmpty, boolean showCourse) {
		if (isEmpty) {
			findViewById(R.id.empty).setVisibility(View.VISIBLE);
			mListCourse.setVisibility(View.INVISIBLE);
			mListSchool.setVisibility(View.INVISIBLE);
		} else if (showCourse) {
			findViewById(R.id.empty).setVisibility(View.INVISIBLE);
			mListCourse.setVisibility(View.VISIBLE);
			mListSchool.setVisibility(View.INVISIBLE);
		} else {
			findViewById(R.id.empty).setVisibility(View.INVISIBLE);
			mListCourse.setVisibility(View.INVISIBLE);
			mListSchool.setVisibility(View.VISIBLE);
		}
	}
	
	private Handler mInitHander = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_CODE_LOAD_FILTERS_CONDITIONS_DONE:
				onLoadFilterConditionsDone();
				break;
			default:
				break;
			}
		};
	};
	
	/// for Refresh and loading more - Start
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			ArrayList<DMCourse> result = (ArrayList<DMCourse>) msg.obj;
			int headTab = msg.arg1;
			switch (msg.what) {
			case AutoListView.REFRESH:
				if (headTab == HEAD_TAB_COURSE) {
					mListCourse.onRefreshComplete();
				} else if (headTab == HEAD_TAB_SCHOOL) {
					mListSchool.onRefreshComplete();
				}
				break;
			case AutoListView.LOAD:
				if (headTab == HEAD_TAB_COURSE) {
					mListCourse.onLoadComplete();
				} else if (headTab == HEAD_TAB_SCHOOL) {
					mListSchool.onLoadComplete();
				}
				break;
			}
			
			if (headTab == HEAD_TAB_COURSE) {
				mListCourse.setResultSize(result.size());
			} else if (headTab == HEAD_TAB_SCHOOL) {
				mListSchool.setResultSize(result.size());
			}
		};
	};
	
	// Course/School List 查询条件
	private SearchCondition mSearchCondition;
	
	// 在course和school切换时，用于记录上次的搜索条件，如未发生变化则不要重新loading数据。
	private SearchCondition mLastSchoolSearchCondition;
	private SearchCondition mLastCourseSearchCondition;
	
	private void loadingAllData(int headTabIndex, int callbackId) {
		if (headTabIndex == 0) {
			loadingAllCourseData(callbackId);
		} else if (headTabIndex == 1) {
			loadingAllSchoolData(callbackId);
		}
	}
	
	private void loadingMoreData(int headTabIndex, int callbackId) {
		if (headTabIndex == 0) {
			loadingMoreCourseDataFromStartIndex(callbackId);
		} else if (headTabIndex == 1) {
			loadingMoreSchoolData(callbackId);
		}
	}
	
	@Override
	public void onLoad() {
		loadingMoreData(mHeadTabSelected, AutoListView.LOAD);
	}

	@Override
	public void onRefresh() {
		loadingAllData(mHeadTabSelected, AutoListView.REFRESH);
	}
	
	/// for Refresh and loading more - End
	
	// init head tab course/school
	private void initHeadTabs() {
		// unselected 对应着选中。
		mHeadTabSelected = 0;
		mActionBar.getCustomView().findViewById(R.id.search_course).setSelected(true);
		mActionBar.getCustomView().findViewById(R.id.search_school).setSelected(false);
		UIHelper.setClickListener(mActionBar.getCustomView(), R.id.search_course, mClickListener);
		UIHelper.setClickListener(mActionBar.getCustomView(), R.id.search_school, mClickListener);
	}
	
	private void selectHeadTab(View arg) {
		if (arg.getId() == R.id.search_course) {
			mHeadTabSelected = 0;
		} else if (arg.getId() == R.id.search_school) {
			mHeadTabSelected = 1;
		}
		
		if (mHeadTabSelected == 0) {
			mActionBar.getCustomView().findViewById(R.id.search_course).setSelected(true);
			mActionBar.getCustomView().findViewById(R.id.search_school).setSelected(false);
			// 课程列表无年龄栏
			findViewById(R.id.head3).setVisibility(View.VISIBLE);
			findViewById(R.id.head3_divider).setVisibility(View.VISIBLE);
			updateSortByText();
			showEmpty(false, true);
		} else if (mHeadTabSelected == 1) {
			mActionBar.getCustomView().findViewById(R.id.search_course).setSelected(false);
			mActionBar.getCustomView().findViewById(R.id.search_school).setSelected(true);
			// 课程列表无年龄栏
			findViewById(R.id.head3).setVisibility(View.GONE);
			findViewById(R.id.head3_divider).setVisibility(View.GONE);
			updateSortByText();
			showEmpty(false, false);
		}
		
		// 如果上次保存的查询条件没变，不执行从新加载数据的动作。
		
		if (mHeadTabSelected == 0) {
			if (mLastCourseSearchCondition != null && mLastCourseSearchCondition.equalsToCourseCondition(mSearchCondition, mHeadTabSelected)) {
				return;
			}
			mLastCourseSearchCondition = mSearchCondition.copy(mHeadTabSelected);
			
			loadingAllCourseData(AutoListView.REFRESH);
		} else {
			if (mLastSchoolSearchCondition != null && mLastSchoolSearchCondition.equalsToSchoolCondition(mSearchCondition, mHeadTabSelected)) {
				return;
			}
			mLastSchoolSearchCondition = mSearchCondition.copy(mHeadTabSelected);
			
			loadingAllSchoolData(AutoListView.REFRESH);
		}
	}
	
	private void forceToReloadData() {
		if (mHeadTabSelected == 0) {
			loadingAllCourseData(AutoListView.REFRESH);
		} else {
			loadingAllSchoolData(AutoListView.REFRESH);
		}
	}

	private void updateSortByText() {
		// update sort by text
		UIHelper.setText(findViewById(R.id.head4), R.id.condition4, 
				SearchCondition.getTag(CourseListActivity.this, mHeadTabSelected, TAB_SMART, mSearchCondition.getColumn4SortBy(mHeadTabSelected), 0));
	}
	
	private int mHeadTabSelected = 0;
	private LoadingAsyncTask<DMSchool> mLoadingSchoolAsyncTask;
	private LoadingAsyncTask<DMCourse> mLoadingCourseAsyncTask;
	private View mSearchFilterBottomView;
	

}
